package com.szt.sy.config.session;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.session.Session;
import org.springframework.session.web.http.CookieHttpSessionStrategy;
import org.springframework.session.web.http.HeaderHttpSessionStrategy;
import org.springframework.session.web.http.HttpSessionStrategy;

/****
 * httpSession策略，同时支持cookie和header
 *
 * @author wwy
 *
 */
public class CookieAndHeaderHttpSessionStrategy implements HttpSessionStrategy {

	public CookieHttpSessionStrategy cookieHttpSessionStrategy = new CookieHttpSessionStrategy();

	public HeaderHttpSessionStrategy headerHttpSessionStrategy = new HeaderHttpSessionStrategy();

	@Override
	public String getRequestedSessionId(HttpServletRequest request) {
		// header part
		String sessionId = headerHttpSessionStrategy.getRequestedSessionId(request);
		if (sessionId != null && !sessionId.isEmpty()) {
			return sessionId;
		}
		// cookie part
		sessionId = cookieHttpSessionStrategy.getRequestedSessionId(request);
		if (sessionId != null && !sessionId.isEmpty()) {
			return sessionId;
		}
		// 从请求参数获取sessionId
		sessionId = request.getParameter("x-auth-token");
		return sessionId;
	}

	@Override
	public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
		// header part
		headerHttpSessionStrategy.onNewSession(session, request, response);
		// cookie part
		cookieHttpSessionStrategy.onNewSession(session, request, response);
	}

	@Override
	public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
		// header part
		headerHttpSessionStrategy.onInvalidateSession(request, response);
		// cookie part
		cookieHttpSessionStrategy.onInvalidateSession(request, response);

	}

}
